package cn.donave.framework.utils;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;

public final class FileHelper {

	private FileHelper() {
	}

	public final static void makeDirectoryByYearMonth(String rootPath) {
		if (rootPath == null)
			return;
		// File file = new File(rootPath + DateHelper.getFileYearMonth());
		// if (!file.isDirectory()) {
		// if (file.mkdirs()) {
		// System.out.println(" make directory sucess!");
		// }
		// }
	}

	public final static void makeDirectory(String path) {
		if (path == null)
			return;
		File file = new File(path);
		if (!file.exists()) {
			if (file.mkdirs()) {
				System.out.println("make directory sucess!" + path);
			}
		}
	}

	public final static void moveFile(File oldFile, String newPath) {
		File fnewpath = new File(newPath);
		if (!fnewpath.exists()) {
			fnewpath.mkdirs();
		}
		File fnew = new File(fnewpath.getPath(), oldFile.getName());
		oldFile.renameTo(fnew);
	}

	public static final void createFile(String webPath, String fileName,
			InputStream fis) {
		if (webPath == null || fileName == null)
			return;
		File filepath = new File(webPath, fileName);
		if (filepath.isFile()) {
			return;
		}
		OutputStream fos = null;
		try {
			fos = new FileOutputStream(filepath);
			int bytesRead = 0;
			byte[] buf = new byte[4 * 1024];
			while ((bytesRead = fis.read(buf)) != -1) {
				fos.write(buf, 0, bytesRead);
			}
			fos.flush();
		} catch (FileNotFoundException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		} finally {
			try {
				if (fos != null)
					fos.close();
				if (fis != null)
					fis.close();
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
	}

}